package com.example.translateappjava.Fragment;

import static android.content.Intent.getIntent;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;

import com.example.translateappjava.Activity.IntroductoryActivity;
import com.example.translateappjava.Activity.LoginActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.AboutUsActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.FeedbackAvtivity;
import com.example.translateappjava.Activity.MineFragmentActivity.MyCollectionsActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.PersonActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.PrivacyGuidelinesActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.SettingsActivity;
import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.Adapter.NewsInfo;
import com.example.translateappjava.R;
import com.example.translateappjava.DataBase.UserInfo;

import java.time.LocalDate;
import java.time.Period;


public class MineFragment extends Fragment {


    private View rootView;
    private TextView name;
    private TextView text_sex;


    private TextView text_age;
    private TextView text_registerDate;
    private TextView text_read;

    private ImageView profileImageView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_mine,container, false);

        name = rootView.findViewById(R.id.name);
        text_sex = rootView.findViewById(R.id.text_sex);
        text_age = rootView.findViewById(R.id.text_age);
        text_registerDate = rootView.findViewById(R.id.keep);
        text_read = rootView.findViewById(R.id.read);
        profileImageView = rootView.findViewById(R.id.profile_image);
        applyColorSettings(rootView);

        ThemeUtilsActivity.applyTheme(rootView);


        RequestOptions requestOptions = new RequestOptions()
                .transform(new RoundedCorners(160)); // 圆角半径

        Glide.with(this)
                .load(R.drawable.fat) // 请替换为您的图像资源ID
                .apply(new RequestOptions()
                        .transform(new RoundedCorners(16)) // 设置圆角半径
                        .error(R.drawable.bmi) // 设置错误图像（可选）
                        .placeholder(R.drawable.ice_latte) // 设置加载图像（可选）
                )
                .into(profileImageView);

        rootView.findViewById(R.id.iv_6).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                new AlertDialog.Builder(getContext())
                        .setMessage("确定要退出登录么？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.remove("is_login");
                                editor.apply();


                                getActivity().finish();
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                            }
                        })
                        .setTitle("温馨提示")
                        .show();
            }

        });


        rootView.findViewById(R.id.to_person).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PersonActivity.class);
                startActivity(intent);
            }
        });

        rootView.findViewById(R.id.collection).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyCollectionsActivity.class);
                startActivity(intent);            }
        });

        rootView.findViewById(R.id.secret).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PrivacyGuidelinesActivity.class);
                startActivity(intent);            }
        });

        rootView.findViewById(R.id.feedback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FeedbackAvtivity.class);
                startActivity(intent);            }
        });

        rootView.findViewById(R.id.about_us).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AboutUsActivity.class);
                startActivity(intent);            }
        });

        rootView.findViewById(R.id.config).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intent);            }
        });

        rootView.findViewById(R.id.viewpager).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), IntroductoryActivity.class);
                startActivity(intent);
            }
        });



        // Inflate the layout for this fragment
        return rootView;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        UserInfo userInfo = UserInfo.getsUserInfo();

        if(null != userInfo){
            String ageString = Integer.toString(userInfo.getAge());
            LocalDate localDate = LocalDate.parse(userInfo.getRegisterDate());
            LocalDate currentDate = LocalDate.now();
            Integer period = Period.between(localDate, currentDate).plusDays(1).getDays(); // 使用时间
            String rdString = Integer.toString(period) + "天";

            // 在MineFragment中，从Intent中获取newsViewCount
            Bundle bundle = getActivity().getIntent().getExtras();
//            if (bundle != null) {
//                int newsViewCount = bundle.getInt("newsViewCount");
//                String readString = newsViewCount + "条";
//                // 使用newsViewCount的值
//                text_read.setText(readString);
//            }



            name.setText(userInfo.getName());
            text_sex.setText(userInfo.getSex());
            text_age.setText(ageString);
            text_registerDate.setText(rdString);
            if (UserInfo.getsUserInfo().getImage() != null)
            {
                Bitmap bitmap = BitmapFactory.decodeByteArray(UserInfo.sUserInfo.getImage(), 0,UserInfo.sUserInfo.getImage().length);
                // 设置 Bitmap 到 ImageView
                profileImageView.setImageBitmap(bitmap);
            }


        }


    }

    @Override
    public void onResume() {
        super.onResume();
        View rootView = getView();
        if (rootView != null) {
            ThemeUtilsActivity.applyTheme(rootView);
        }
        UserInfo userInfo = UserInfo.getsUserInfo();
        LocalDate birthDate = LocalDate.parse(UserInfo.sUserInfo.getBirth());
        LocalDate currentDate1 = LocalDate.now();
        String ageString = Integer.toString(Period.between(birthDate, currentDate1).getYears());

        LocalDate localDate = LocalDate.parse(userInfo.getRegisterDate());
        LocalDate currentDate = LocalDate.now();
        Integer period = Period.between(localDate, currentDate).plusDays(1).getDays(); // 使用时间
        String rdString = Integer.toString(period) + "天";
        name.setText(userInfo.getName());
        text_sex.setText(userInfo.getSex());
        text_age.setText(ageString);
        text_registerDate.setText(rdString);
        System.out.println(UserInfo.sUserInfo.getImage());
        System.out.println(UserInfo.sUserInfo.getSex());
        System.out.println(Period.between(birthDate, currentDate).getYears());
        System.out.println(UserInfo.sUserInfo.getBirth());

        if (UserInfo.getsUserInfo().getImage() != null)
        {
            Bitmap bitmap = BitmapFactory.decodeByteArray(UserInfo.sUserInfo.getImage(), 0,UserInfo.sUserInfo.getImage().length);
            // 设置 Bitmap 到 ImageView
            profileImageView.setImageBitmap(bitmap);
        }

    }
    private void applyColorSettings(View rootView) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        int defaultColor = getResources().getColor(R.color.toolbar_color); // 默认颜色
        int color = sharedPreferences.getInt("color", defaultColor); // 如果未找到颜色，则使用默认颜色
        Toolbar toolbar = rootView.findViewById(R.id.toolbar);

        // 应用颜色到您想要更改的视图
        toolbar.setBackgroundColor(color);

        // 如果有其他视图也需要应用颜色，也可以在这里设置
    }



}